define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');

	var List = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"class": 'P-creative'
				,"urlUpload": 'creativeAudit/reUpload'
			});

			this.Super('init', arguments);
			this.$param = {};
		},
		afterBuild:function(){
			var self = this;
			var title = self.getConfig('idType') ? LANG('创意终审(非汇总)'):LANG('创意终审');
			this.append($([
				'<div class="M-formHead">',
					'<label class="M-formHeadTitle">'+ title +'</label>',
					'<span class="fl" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="highGrid" pub-mod="creative/grid/creativeAudit.base"/>'
			].join('')));

			var endTime = parseInt(Date.now()/1000);
			var beginTime = parseInt(new Date(endTime * 1000 - 6 * 24 * 3600 * 1000) /1000);//默认显示一周内的创意

			var cfg = {
				'date':{
					'pos': 'bR',
					'broadcast':false,
					'userStorage':false,
					'hasNoLimit':true,
					'begin':beginTime,
					'end':endTime,
					'buttons':[
						{
							// 显示的文字
							"text":LANG("今天"),
							"begin":0,
							"end":0,
							"type":"today"
						},
						{
							"text":LANG("昨天"),
							"begin":-1,
							"end":-1,
							"type":"yesterday"
						},
						{
							"text":LANG("最近7天(含今天)"),
							"begin":-6,
							"end":0,
							"type":"latestSeven"
						},
						{
							"text":LANG("最近30天(含今天)"),
							"begin":-29,
							"end":0,
							"type":"latestThirty"
						},
						{
							"text":LANG("本月"),
							"begin":0,
							"end": -(new Date()).getDate(),
							// 特殊指定操作类型
							"type":"currentMonth"
						}
					]
				},
				'highGrid':{
					'hasSearch': false,
					'idType':self.getConfig('idType'),
					'param':{
						'begindate':beginTime,
						'enddate':endTime
					}
				}
			};

			self.buildFromTemplate(cfg);
			self.createAsync('creativePreview','creative/popwin/auditEdit.base',{idType:self.getConfig('idType')}, function( mod ) {
				self.$.editPopwin = mod;
			});

			self.createAsync('batchEdit' + (self.getConfig('idType')|| ''),'creative/popwin/batchAuditEdit.base', {idType:self.getConfig('idType')},function( mod ) {
				self.$.batchAuditEditPopwin = mod;
			});

			var config = this.getConfig();
			var items = [
				{'name': 'searchUserName', 'uri':'modules/sideBarBase.search',config:{
					name:'userNameWord',
					searchTip:"账号名称",
					parentClass: 'dib'
				}},
				{'name': 'searchSweety', 'uri':'modules/sideBarBase.search',config:{
					searchTip:"创意包关键字",
					name:'sweetyWord',
					parentClass: 'dib'
				}},

				{'name': 'searchCreative', 'uri':'modules/sideBarBase.search',config:{
					name:'creativeWord',
					searchTip:"创意关键字",
					parentClass: 'dib'
				}},

				{'name': 'creativeType', 'uri':'modules/sideBarBase.radio', 'config': {
					'title': LANG('类型：'),
					'data': [
						{id: 0, name: LANG('非代码创意')},
						{id: 4, name: LANG('代码创意')}
					],
					'value': 0
				}},

				//TODO: 加载渠道
				{'name': 'channelId', 'uri':'modules/sideBarBase.channel','config':{'monitorUrl':''}},
				{'name': 'status', 'uri':'modules/sideBarBase.radio', 'config': {
					'title': LANG('总状态：'),
					'data': [
						{id : '-100', name: LANG('所有状态')},
						{id : '-3', name: LANG('预审审核中(灰)')},
						{id : '1,2', name: LANG('审核中(蓝)')},
						{id : '3', name: LANG('通过(绿)')},
						{id : '-2,-1', name: LANG('拒绝(红)')}
					],
					'value': '-100'
				}}
			];

			if(self.getConfig('idType') ){
				//非汇总才加渠道审核参数
				items.push({'name': 'subStatus', 'uri':'modules/sideBarBase.radio', 'config': {
					'title': LANG('渠道审核：'),
					'data': [
						{id: -3, name: LANG('所有状态')},
						{id: 0, name: LANG('待审核(灰)')},
						{id: -2, name: LANG('审核中(蓝)')},
						{id: 1, name: LANG('通过(绿)')},
						{id: -1, name: LANG('拒绝(红)')}
					],
					'value': -3
				}});
			}

			self.createAsync('sidebar', '@layout/v1/sidebar.base', {
				'target': config.targetSidebar,
				'items':items
			}, function(){});


		},
		// 批量操作-下拉菜单界面
		onBatchShow: function(ev){
			ev.returnValue = [];

			if(pubjs.checkRight('creative.getAudit')){
				ev.returnValue.push({id: 'getAuditResult', name: LANG('获取审核结果')});
			}
			if(pubjs.checkRight('creative.preAudit')){
				ev.returnValue = ev.returnValue.concat( [
					{id: 'audit', name: LANG('预审')}
					,{id: 'preReject', name: LANG('(预审)拒绝')}
				])
			}
			if(pubjs.checkRight('creative.audit')){
				ev.returnValue.push({id: 'reAudit', name: LANG('重新送审')})
			}

			return false;
		},
		// 批量操作-响应菜单操作
		onBatchSelect: function(ev){
			var data = ev.param[0];
			var ids = ev.param[1];
			var creatives = ev.param[2];

			var key = data.key || '';

			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择创意'));
				return false;
			}

			if(~['reAudit', 'getAuditResult'].indexOf(key))
			{
				for(var i = 0; i < creatives.length; i++)
				{
					if(creatives[i] && creatives[i].youku_info)
					{
						return pubjs.alert(LANG('创意 %1 本地未上传成功，请不要去获取状态或重新送审', creatives[i].Name));
					}
				}
			}

			switch(key){
				case 'audit':
					this.$.batchAuditEditPopwin.setMode('preAudit').setData({ids:ids,creatives:creatives}).show();
					break;
				case 'preReject':
					this.$.batchAuditEditPopwin.setMode('preAudit').setData({ids:ids,creatives:creatives,status:-1,preInfo:"(终审页面)手工拒绝审核"}).show();
					break;
				case 'getAuditResult':
					this.$.batchAuditEditPopwin.setMode('getAuditResult').setData({ids:ids,creatives:creatives}).show();
					break;
				case 'reAudit':
					this.$.batchAuditEditPopwin.setMode('audit').setData({ids:ids,creatives:creatives}).show();
					break;
			}
			return false;
		},

		// 操作列点击事件
		onOperateMenuShow: function(ev) {

			var returnList = [];
			var data = ev.param;

			if(data.youku_info)
			{
				if(data.youku_info.state === 0 && pubjs.checkRight('creative.reUpload'))
				{
					returnList.push({
						'id': 'reUpload',
						'name': LANG('重新上传')
					});
				}

				if(!returnList.length)
				{
					returnList.push({
						'id': '',
						'name': LANG('没有权限')
					});
				}
			}
			else
			{
				if(pubjs.checkRight('creative.getAudit')){
					returnList.push({
						'id': 'getAuditResult',
						'name': LANG('获取审核结果')
					})
				}

				if(pubjs.checkRight('creative.preAudit')){
					returnList = returnList.concat([
						{
							'id': 'audit',
							'name': LANG('审核')
						},
						{
							'id': 'reject',
							'name': LANG('拒绝')
						},
						{
							'id': 'preAudit',
							'name': LANG('预审核')
						}
					]);
				}

				if(!returnList.length)
				{
					returnList.push({
						'id': '',
						'name': LANG('没有权限')
					});
				}
			}

			ev.returnValue = returnList;
			return false;
		},
		// 操作列选项点击事件
		onOperateMenuSelect: function(ev) {
			var self = this;
			var key = ev.param[0]['key'];
			var c = self.getConfig();

			var createive = ev.param[1];
			// var id = +ev.param[1]['_id'];
			switch (key){
				case 'audit':
					self.$.editPopwin.setData(createive).setMode('audit').show();
					break;
				case 'getAuditResult':
					self.$.editPopwin.setData(createive).setMode('getAuditResult').show();
					break;
				case 'reject':
					this.$.editPopwin.setData(createive).setMode('preAudit').setReject("(终审页面)手工拒绝审核").show();
					break;
				case 'preAudit':
					this.$.editPopwin.reset().setData(createive).setMode('preAudit').show();
					break;
				case 'reUpload':
					pubjs.confirm(LANG('确认要重新上传素材吗'), function(state) {
						if(state)
						{
							pubjs.loading.show();
							pubjs.mc.send(c.urlUpload, {id: createive._id}, function(err, data) {
								pubjs.loading.hide();
								if(err)
								{
									return pubjs.alert(err.message);
								}

								pubjs.alert(LANG('操作成功'));
								self.$.highGrid.reload();
							});
						}
					});
					break;
			}
			return false;
		},
		onSidebarFilter: function(ev){
			var self = this
			var param = this.$param;
			
			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;
				switch (type) {
					case 'creativeType':
					case 'channelId':
					case 'subStatus':
						param[type] = +id;
						break;
					case 'status':
						param[type] = id;
				}
			});

			if(this.get('sidebar/searchUserName')){
				param.userNameWord = this.get('sidebar/searchUserName').getValue();
			}
			if(this.get('sidebar/searchSweety')){
				param.sweetyWord = this.get('sidebar/searchSweety').getValue();
			}
			if(this.get('sidebar/searchCreative')){
				param.creativeWord = this.get('sidebar/searchCreative').getValue();
			}

			this.$.highGrid.reload(param,null,1);
		},
		onSearch: function(ev){
			this.$param[ev.name] = ev.param || '';
			 //刷新页码
			this.$.highGrid.reload(this.$param,null,1);
			return false;
		},
		reload: function(param){
			param = param || {};
			this.$.highGrid.reload(param);
			return this;
		},
		onEditSuccess:function(){
			this.$.highGrid.reload();
		},
		editPopwin:function(adExchange){
			var self = this;
			if (self.$.editPopwin) {
				self.$.editPopwin.setData(adExchange).show();
			}
		},
		onAuditSuccess: function(ev){
			if(this.$.highGrid){
				this.$.highGrid.setSelectRowIds([]);
				this.reload();
			}
		},
		onDateRangeChange:function (ev) {
			var param = ev.param;
			if(param.nowTimestamp ){
				var timeStamp = param.nowTimestamp;
				this.$.highGrid.reload({'begindate':timeStamp.begindate,'enddate':timeStamp.enddate},null,1);
			}
			return false;
		}
	});

	exports.main = List;
});